package com.share.user.controller;


import cn.hutool.json.JSONObject;
import com.share.BaseReponse;
import com.share.filter.JWTUtil;
import com.share.filter.ThreadLocalModel;
import com.share.user.model.SyUser;
import com.share.user.service.SyUserService;
import com.share.filter.RedisUtil; // 引入 Redis 工具类
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author 小赵
 * @version 1.0
 * @data 2024-12-13 10:18
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class A {
    @Autowired
    private SyUserService syUserService;

    // 登录接口
    @PostMapping
    public ResponseEntity<BaseReponse> login(@RequestBody SyUser syUser) {
        String username = syUser.getUsername();
        String password = syUser.getPassword();

        if (isNullOrEmpty(username) || isNullOrEmpty(password)) {
            return ResponseEntity.badRequest()
                    .body(BaseReponse.error("用户名或密码不能为空"));
        }

        boolean loginSuccess = syUserService.login(username, password);
        if (loginSuccess) {
            Long userId = syUserService.getUserIdByUsername(username).getId();
            if (userId == null) {
                return ResponseEntity.internalServerError()
                        .body(BaseReponse.error("无法获取用户ID"));
            }

            Long fileId = 0L;
            Long binId = 0L;
            String token = JWTUtil.createToken(userId, fileId, binId);

            // 将token存储到Redis中
            RedisUtil.setToken(userId.toString(), token);

            JSONObject data = new JSONObject();
            data.put("token", token);
            return ResponseEntity.ok(BaseReponse.success(data));
        } else {
            log.info("登录失败: 用户名或密码错误");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(BaseReponse.error("用户名或密码错误"));
        }
    }

    @GetMapping
    public BaseReponse info(@RequestHeader("token") String token) {
        log.info("进入获取用户信息方法");

        if (isNullOrEmpty(token)) {
            log.error("Token不能为空");
            return BaseReponse.error("Token不能为空");
        }

        // 验证 token
        if (!JWTUtil.verifyToken(token)) {
            log.error("无效的token");
            return BaseReponse.error("无效的token");
        }

        // 获取 ThreadLocal 数据
        ThreadLocalModel model = JWTUtil.getThreadLocalModel();
        if (model == null) {
            log.error("ThreadLocalModel is null, token may be invalid");
            return BaseReponse.error("无效的token");
        }

        // 从Redis获取token并检查
        String redisToken = RedisUtil.getTokenByUserId(model.getUserID().toString());
        if (redisToken == null || !redisToken.equals(token)) {
            log.error("Token在Redis中不存在或不一致");
            return BaseReponse.error("无效的token");
        }

        // 创建返回 JSON 对象
        JSONObject data = new JSONObject();
        data.put("user_id", model.getUserID());
        data.put("file_id", model.getFileID());
        data.put("bin_id", model.getBinID());

        return BaseReponse.success(data);
    }

    // 检查字符串是否为空
    private boolean isNullOrEmpty(String str) {
        return str == null || str.isEmpty();
    }
}


